import { createElement, useEffect, useState, useRef } from 'rax';
import { usePageShow } from 'rax-app';
import View from 'rax-view';
import Image from 'rax-image';
import Text from 'rax-text';
import {
  queryTemplatesList,
  queryUserInfo,
  queryUserArchivesList,
  postAddTask,
  postTbLogin,
  queryUserPoints
} from '@/api';
import { query } from '../../api/fetch';
import {
	getStorageSync,
	setStorageSync,
} from '@/utils/util';
// import { tb } from 'taobao-sdk'
import ModalMakeing from '@/components/ModalMakeing';
import ModalMyFace from '@/components/ModalMyFace';
import ModalTask from '@/components/ModalTask';
import ModalTemplate from '@/components/ModalTemplate';
import NavBar from '@/components/NavBar';
import Guide from '@/components/Guide';
import Double from '@/components/Double';
import JoinMember from '@/components/JoinMember';
import PhoneLogin from '@/components/PhoneLogin';
import './index.css';

const Home = () => {
  const [showGuide, setShowGuide] = useState(false);
  const [isLogined, setIsLogined] = useState(false);
  const [showDouble, setShowDouble] = useState(false);
  const [showMember, setShowMember] = useState(false);
  const [statusBarHeight, setStatusBarHeight] = useState(0);
  const [userInfo, setUserInfo] = useState({});
  const [show, setShow] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [showTip, setShowTip] = useState(false);
  const [modal, setModal] = useState({
    showTemmplate: false,
    showMakeing: false,
    showMyFace: false,
    showTask: false,
  });
  const [checked, setChecked] = useState(false);
  const [list, setList] = useState([]);
  const app = getApp();
  const [isFavor, setIsFavor] = useState(app.globalData.isFavorShop);
  const [myPortrayList, setMyPortrayList] = useState([]);
  const [portrayId, setPortrayId] = useState(null);
  const [current, setCurrent] = useState(0);
  const [backdropImg, setBackdropImg] = useState('');
  const [template, setTemplate] = useState('');
  const [templateName, setTemplateName] = useState('');
  const [templateUse, setTemplateUse] = useState('');
  const [num, setNum] = useState(1);
  const [leftface, setLeftFace] = useState('');
  const [leftName, setLeftName] = useState('');
  const [rightface, setRightFace] = useState('');
  const [rightName, setRightName] = useState('');
  const [faceType, setFaceType] = useState('leftface');
  const [canSubmit, setCanSubmit] = useState(true);
  const [point, setPoint] = useState(0);
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');

  usePageShow(() => {
    let hasGuide = getStorageSync('hasGuide');
    if (hasGuide) {
      setShowGuide(false);
    } else {
      setShowGuide(true);
    }
    my.setCanPullDown({
      canPullDown: false
    });
    onLoadUser();
    if (isLogined) {
      my.tb.checkShopFavoredStatus({
        id: 1652554937,
        success: (res) => {
          setIsFavor(res.isFavor);
        },
        fail: (err) => {
          console.log('err', err)
        }
      })
    }
    my.getSystemInfo({
      success: (res) => {
        setStatusBarHeight(res.statusBarHeight + res.titleBarHeight / 2)
      }
    });
    if (app.globalData.needRelaodFaceprofile) {
      onLoadArchivesList();
      onCloseTemplate();
      app.globalData.needRelaodFaceprofile = false;
    }
    if (app.globalData.templateInfo.tmpl_id) {
      let {
        tmpl_name,
        tmpl_id,
        tmpl_img,
        tmpl_tmb_img,
        number,
        use_num,
        backdrop_img
      } = app.globalData.templateInfo;
      setBackdropImg(backdrop_img);
      setTemplateName(tmpl_name);
      setCurrent(tmpl_id);
      setTemplate(tmpl_img);
      setNum(number);
      setTemplateUse(use_num);
      onCloseMakeing();
      app.globalData.templateInfo = {};
    }
  });

  useEffect(()=>{
    console.log('app.globalData', app.globalData)
    if (app.globalData.isShareDouble) {
      onShare();
    }
  }, [app.globalData])

  useEffect(()=>{
    my.hideTabBar();
    onLoadPoint();
    onLoadTemplates();
  }, []);

  const onLoadPoint = () => {
    queryUserPoints({})
      .then(res=>{
        setPoint(res.currentPoint);
      })
  }

  const onLoadUser = () => {
    queryUserInfo()
      .then(res=>{
        if (res.Code == 403) {
          setIsLogined(false)
        } else {
          setIsLogined(true);
          onLoadArchivesList();
          setUserInfo(res);
          my.tb.checkShopFavoredStatus({
            id: 1652554937,
            success: (res) => {
              setIsFavor(res.isFavor);
            },
            fail: (err) => {
              console.log('err', err)
            }
          })
        }
      })
  }

  const onLoadTemplates = () => {
    queryTemplatesList({})
      .then(res=>{
        setList(res.list);
        setBackdropImg(res.list[0].backdrop_img);
        setTemplate(res.list[0].img);
        setCurrent(res.list[0].id);
        setTemplateName(res.list[0].tmpl_name);
        setTemplateUse(res.list[0].use_num);
      })
  }

  const onChooseTemplate = (id, url, number, tmpl_name, use_num, backdrop_img) => {
    setCurrent(id);
    setTemplate(url);
    setNum(number);
    setTemplateName(tmpl_name);
    setTemplateUse(use_num);
    setBackdropImg(backdrop_img);
  }

  const debounce = (func, wait) =>{
    let timeout;
    return function() {
      if (timeout) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(() => {
        func.apply(this, arguments);
      }, wait);
    };
  }

  const showMyPortray = () => {
    if (isLogined) {
      my.navigateTo({
        url: '/pages/portray/index',
      })
    } else {
      setShowLogin(true);
    }
  }

  const showPersonCenter = () => {
    if (isLogined) {
      my.navigateTo({
        url: '/pages/mine/index',
      })
    } else {
      setShowLogin(true);
    }
  }

  const onAuthorize = () => {
    if (isLogined) {
      my.navigateTo({
        url: '/pages/task/index'
      })
    } else {
      setShowLogin(true);
    }
  }

  const onClose = () => {
    setShow(false);
  }

  const onHandleLogin = (event) => {
    event.stopPropagation();
    my.authorize({
      scopes: 'scope.userInfo',
      success: (res) => {
        // setStorageSync('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDA3MjM3NTMsIm5iZiI6MTcwMDcyMzc1MywiZXhwIjoxNzAzMzE1NzUzLCJ1aWQiOiIxMDAxOCJ9.Gl75Xttfetdn5c6tw_Q5EGN7bI2lXh8K4qCS28A1HSI')
        // setStorageSync('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDA4MzE0ODQsIm5iZiI6MTcwMDgzMTQ4NCwiZXhwIjoxNzAzNDIzNDg0LCJ1aWQiOjEwMDA0fQ.UIIAiYcyzLCWrQseYY4LVpD36EDRgvQcO7QRiFsxBtQ')
        setStorageSync('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDEwOTIxMTcsIm5iZiI6MTcwMTA5MjExNywiZXhwIjoxNzAzNjg0MTE3LCJ1aWQiOiIxMDAxOCJ9.pTiXmjXbxPzYQ8aW2QuBKf8pYANWyhz5gajwoaOtta8')
        onLoadUser();
        setShowLogin(false);
        setShowTip(false);
      }
    });
  }

  const doLogin = (event) => {
    event.stopPropagation();
    if (checked) {
      my.authorize({
        scopes: 'scope.userInfo',
        success: (res) => {
          // setStorageSync('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDA3MjM3NTMsIm5iZiI6MTcwMDcyMzc1MywiZXhwIjoxNzAzMzE1NzUzLCJ1aWQiOiIxMDAxOCJ9.Gl75Xttfetdn5c6tw_Q5EGN7bI2lXh8K4qCS28A1HSI')
          // setStorageSync('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDA4MzE0ODQsIm5iZiI6MTcwMDgzMTQ4NCwiZXhwIjoxNzAzNDIzNDg0LCJ1aWQiOjEwMDA0fQ.UIIAiYcyzLCWrQseYY4LVpD36EDRgvQcO7QRiFsxBtQ')
          setStorageSync('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDEwOTIxMTcsIm5iZiI6MTcwMTA5MjExNywiZXhwIjoxNzAzNjg0MTE3LCJ1aWQiOiIxMDAxOCJ9.pTiXmjXbxPzYQ8aW2QuBKf8pYANWyhz5gajwoaOtta8')
          onLoadUser();
          setShowLogin(false);
          setShowTip(false);
        }
      });
    } else {
      my.showToast({
        content: '请先同意并勾选协议',
        type: 'none',
        zIndex: 9999
      });
    }
  }

  const onRejectLogin = () => {
    setShowLogin(false);
    setShowTip(true);
  }

  const onStillReject = () => {
    setShow(false);
    setShowLogin(false);
    setShowTip(false);
  }

  const onChooseProtocol = (event) => {
    event.stopPropagation();
    setChecked(!checked);
  }

  const onLoadArchivesList = () => {
    queryUserArchivesList()
      .then(res => {
        console.log('queryUserArchivesList', res.list)
        setMyPortrayList(res.list);
        let data = res.list.filter(item=>{
          return item.id === portrayId
        })
        if (data.length === 0) {
          setLeftFace('');
          setLeftName('');
          setPortrayId(null);
          setRightFace('');
          setRightName('');
        }
      })
  }

  const onStart = () => {
    if (isLogined) {
      if (myPortrayList.length == 0) { 
        setModal({
          showTemmplate: true,
          showMyFace: false,
          showTask: false,
          showMakeing: false,
        })
      } else {
        setModal({
          showTemmplate: false,
          showMyFace: true,
          showTask: false,
          showMakeing: false,
        })
      }
    } else {
      setShowLogin(true);
    }
  }

  const onChoosePortrayId = (id) => {
    setPortrayId(id);
  }

  const onChooseItem = (e) => {
    onChoosePortrayId(e.id);
    if (faceType == 'leftface') {
      setLeftFace(e.img);
      setLeftName(e.name);
    } else {
      setRightFace(e.img);
      setRightName(e.name);
    }
    setModal({
      showTemmplate: false,
      showTask: false,
      showMakeing: false,
      showMyFace: true,
    })
  }

  const onMakeing = () => {
    let params = {
      template_id: current,
      face_imgs: [leftface],
    }
    if (num == 2) {
      params.face_imgs = [leftface, rightface];
    }
    if (!leftface || (num == 2 && !rightface)) {
      my.showToast({
        content: '请选择脸部档案',
        type: 'none',
        zIndex: 9999
      })
      return
    }
    if (canSubmit) {
      setCanSubmit(false)
      postAddTask(params)
        .then(res=>{
          if (res.Code == 452) {
            setCanSubmit(true);
            my.showToast({
              content: '没有作图次数',
              type: 'none',
              zIndex: 9999
            })
            onOpenTask();
          }
          if (res && res.TaskId) {
            setCanSubmit(true);
            my.navigateTo({
              url: `/pages/makeing/index?taskId=${res.TaskId}`,
            });
          }
        })
        .catch(err=> {
          setCanSubmit(true);
        })
    }
  }

  const onCloseTemplate = () => {
    setModal({
      showTemmplate: false,
      showMyFace: false,
      showTask: false,
      showMakeing: true,
    })
  }

  const onCloseMakeing = () => {
    setModal({
      showTemmplate: false,
      showTask: false,
      showMakeing: false,
      showMyFace: true,
    })
  }

  const onAddMakeing = (e) => {
    setModal({
      showTask: false,
      showMakeing: false,
      showMyFace: false,
      showTemmplate: true,
    })
  }

  const onCloseMyFace = () => {
    setModal({
      showTask: false,
      showMakeing: false,
      showMyFace: false,
      showTemmplate: false,
    })
  }

  const onOpenTask = () => {
    setModal({
      showMakeing: false,
      showMyFace: false,
      showTemmplate: false,
      showTask: true,
    })
  }

  const onCloseTask = () => {
    setModal({
      showTask: false,
      showMakeing: false,
      showTemmplate: false,
      showMyFace: true,
    })
  }

  const onShare = () => {
    setShowTemplate(false);
    setShowMyFace(false);
    setShowMakeing(false);
    setShowTask(false);
    setShowDouble(true);

  }

  const onJoin = () => {
    my.tb.navigateToTaobaoPage({
      appCode:'shop',
      appParams:{
        shopId: "103715363",
        weexShopTab: "shopindexbar",
        weexShopSubTab: "shopindex"
      },
      success: (res) => {
        setShowMember(false)
      },
      fail: (res) => {
        console.log(123)
      }
    });
  }

  const onInput = (event) => {
    let {
      value,
      type
    } = event;
    if (type == 'phone') {
      setPhone(value);
    } else {
      setCode(value);
    }
  }

  return (
    <View
      className='home_view'
      style={{
        backgroundImage: `url(${backdropImg})`
      }}
    >
      <View
        className='home_view_status'
        style={{
          height: `${statusBarHeight}px`
        }}
      ></View>
      <View
        className='home_view_main'
        style={{
          paddingTop: `${statusBarHeight}px`
        }}
      >
        <View className='home_view_content'>
          <Image
            source={{
              uri: 'https://jala-test-images.sndaurl.cn/images/LogoBrand.png'
            }}
            mode='aspectFill'
            className='home_view_content_logo'
          />
          <View className='home_view_content_action'>
            <View className='home_view_content_action_info'>
              剩余变妆
              <Text className='home_view_content_action_remain'>
                {userInfo?.num ? userInfo?.num > 99 ? '9+' : userInfo?.num : '-'}
              </Text>
              次
            </View>
            <View
              className='home_view_content_action_get'
              onClick={()=>{
                onAuthorize()
              }}
            >
              去获取
              <Image
                source={{
                  uri: 'https://jala-test-images.sndaurl.cn/images/right.png'
                }}
                mode='aspectFill'
                className='home_view_content_action_get_icon'
              />
            </View>
          </View>
        </View>
        <View className='home_view_section'>
          <Image
            source={{
              uri: template
            }}
            mode='aspectFill'
            className='home_view_section_img'
          />
        </View>
        <View className='home_view_container'>
          <View className='home_view_container_templates'>
            {
              list.map(item=>
                <View
                  className={`home_view_container_templates_item ${item.id == current ? 'active' : ''}`}
                  key={item.id}
                  onClick={()=>{
                    onChooseTemplate(item.id, item.img, item.number, item.tmpl_name, item.use_num, item.backdrop_img)}
                  }
                >
                  <View className='home_view_container_templates_item_section'>
                    <Image
                      source={{
                        uri: item.tmb_img
                      }}
                      mode='aspectFill'
                      className='home_view_container_templates_item_img'
                    />
                    <View
                      className='home_view_container_templates_item_text'
                    >
                      {item.tmpl_name}
                    </View>
                  </View>
                </View>
              )
            }
          </View>
          <View className='home_view_container_actions'>
            <View className='home_view_container_actions_item' onClick={()=>{debounce(showMyPortray(), 300)}}>
              <Image
                source={{
                  uri: 'https://jala-test-images.sndaurl.cn/images/AI.png'
                }}
                mode='aspectFill'
                className='home_view_container_actions_item_icon'
              />
              <View className='home_view_container_actions_item_text'>我的写真</View>
            </View>
            <View
              className='home_view_container_actions_btn'
              catchTouchMove
              onClick={()=>{
                debounce(onStart(), 300)
              }}
            >
              选择模版开启变妆
            </View>
            <View
              className='home_view_container_actions_item'
              onClick={()=>{
                debounce(showPersonCenter(), 300)
              }}
            >
              <Image
                source={{
                  uri: 'https://jala-test-images.sndaurl.cn/images/userCenter.png'
                }}
                mode='aspectFill'
                className='home_view_container_actions_item_icon'
              />
              <View className='home_view_container_actions_item_text'>个人中心</View>
            </View>
          </View>
        </View>
      </View>
      {
        showTip ? (
          <View
            className='mask'
          >
            <View className='modal_tip'>
              <View className='modal_tip_title'>温馨提示</View>
              <View className='modal_tip_content'>
                为更好的保护您的个人信息安全，需要您阅读并同意<Text className='modal_tip_content_link'>《用户服务协议》</Text>和<Text className='modal_tip_content_link'>《隐私政策》</Text>。
                我们将严格按照各项条款适用和保护您的个人信息。
              </View>
              <View className='modal_tip_content mb48'>若您“仍不同意”，我们将无法为您提供完整服务。</View>
              <View className='modal_tip_action'>
                <View
                  className='modal_tip_action_item cancel'
                  onClick={()=>{onStillReject()}}
                >
                  仍不同意
                </View>
                <View
                  className='modal_tip_action_item sure'
                  onClick={(e)=>{onHandleLogin(e)}}
                >
                  同意并登录
                </View>
              </View>
            </View>
          </View>
        ) : null
      }
      {/* {
        showLogin ? (
          <View
            className='mask'
          >
            <View className={`modal_view`}>
              <Image
                source={{
                  uri: 'https://jala-test-images.sndaurl.cn/images/gift.png'
                }}
                mode='aspectFill'
                className='modal_view_icon'
              />
              <View className='modal_view_title'>
                <Image
                  source={{
                    uri: 'https://jala-test-images.sndaurl.cn/images/logo.png'
                  }}
                  mode='aspectFill'
                  className='modal_view_title_logo'
                />
                <Text className='modal_view_title_name'>加入会员 享新人礼</Text>
              </View>
              <View className='modal_view_subtitle'>隐私政策说明</View>
              <View className='modal_view_detail'>
                <Image
                  source={{
                    uri: checked ? 'https://jala-test-images.sndaurl.cn/images/checkmark.png' : 'https://jala-test-images.sndaurl.cn/images/unchecked.png'
                  }}
                  mode='aspectFill'
                  className='modal_view_detail_icon'
                  onClick={(e)=>{onChooseProtocol(e)}}
                />
                <View className='modal_view_detail_content'>
                  请您仔细阅读
                  <Text className='modal_view_detail_content_link'>《用户服务协议》</Text>和
                  <Text className='modal_view_detail_content_link'>《隐私政策》</Text>。我们将申请您的授权，获取您的手机号用于注册自然堂会员，享受相关权益。阅读后请您勾选左侧按钮，并点击 “同意并登录”，即表示您已阅读并同意上述条款。
                </View>
              </View>
              <View className='modal_view_action'>
                <View
                  className='modal_view_action_login'
                  onClick={(e)=>{doLogin(e)}}
                >
                  同意并登录
                </View>
                <View className='modal_view_action_cancel' onClick={()=>{onRejectLogin()}}>不同意</View>
              </View>
            </View>
          </View>
        ) : null
      } */}
      {
        showLogin ? (
          <PhoneLogin
            phone={phone}
            code={code}
            onInput={(e)=>{onInput(e)}}
          />
        ) : null
      }
      {
        modal.showTemmplate ? (
          <ModalTemplate
            onClose={()=>{onCloseTemplate()}}
          />
        ) : null
      }
      {
        modal.showMakeing ? (
          <ModalMakeing
            myPortrayList={myPortrayList}
            portrayId={portrayId}
            onChooseItem={(e)=>{onChooseItem(e)}}
            onAdd={(e)=>{onAddMakeing(e)}}
            onClose={()=>{onCloseMakeing()}}
          />
        ) : null
      }
      {
        modal.showMyFace ? (
          <ModalMyFace
            onClose={()=>{onCloseMyFace()}}
            template={template}
            templateName={templateName}
            templateUse={templateUse}
            leftName={leftName}
            rightName={rightName}
            onUpload={(e)=>{
              let type = e.type;
              e.event.stopPropagation();
              setFaceType(type);
              setModal({
                showTask: false,
                showMakeing: true,
                showMyFace: false,
                showTemmplate: false,
              })
            }}
            onRemove={(e)=>{
              let type = e.type;
              if (type === 'leftface') {
                setLeftFace('');
                setLeftName('');
              } else {
                setRightName('');
                setRightFace('');
              }
            }}
            num={num}
            leftface={leftface}
            rightface={rightface}
            onMakeing={()=>{onMakeing()}}
            onShare={()=>{onShare()}}
          />
        ) : null
      }
      {
        modal.showTask ? (
          <ModalTask
            isFavor={isFavor}
            onChangeFavor={(e)=>{
              let isFavor = e.isFavor;
              setIsFavor(isFavor);
            }}
            point={point}
            userInfo={userInfo}
            onClose={()=>{onCloseTask()}}
            onReload={()=>{onLoadUser()}}
          />
        ) : null
      }
      {
        showGuide ? (
          <Guide
            onClose={()=>{setShowGuide(false)}}
          />
        ) : null
      }
      {
        showDouble ? (
          <Double
            onClick={()=>{setShowDouble(false)}}
          />
        ) : null
      }
      {
        showMember ? (
          <JoinMember
            onClose={()=>{setShowMember(false)}}
            onJoin={()=>{onJoin()}}
          />
        ) : null
      }
    </View>
  )
}

export default Home;
